﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;

namespace BasePlatformCommon {
    public abstract class JsonClassBase<T> {
        /*
         * JSON相关
         */
        public override string ToString() {/*{{{*/
            var json = JsonConvert.SerializeObject(this, new JsonSerializerSettings {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Auto
            });

            return json;
        }/*}}}*/

        public string ToString(bool trim) {/*{{{*/
            if (!trim) {
                return this.ToString();
            }
            var json = JsonConvert.SerializeObject(this, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto
            });

            return json;
        }/*}}}*/

        public static T FromString(string json) {/*{{{*/
            T inst = default(T);

            try {
                inst = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
            }
            catch (Exception ex) {
                Console.WriteLine("Exception: {0}", ex.Message);
            }

            return inst;
        }/*}}}*/

        public void SaveToFile(string path) {/*{{{*/
            using (var sw = File.CreateText(path)) {
                sw.WriteLine(ToString());
            }
        }/*}}}*/

        public static T LoadFromFile(string path) {/*{{{*/
            var json = "";

            try {
                using (var sr = File.OpenText(path)) {
                    json = sr.ReadToEnd();
                }
            }
            catch (Exception ex) {
                Console.WriteLine(">>>> Exception: {0}", ex.Message);
                return default(T);
            }

            return FromString(json);
        }/*}}}*/

        public T Clone() {/*{{{*/
            return FromString(ToString());
        }/*}}}*/
    }
}
